package com.tengroup.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tengroup.dao.UsersDao;
import com.tengroup.entity.UserInfoEntity;
import org.springframework.stereotype.Service;
import com.tengroup.security.PasswordUtils;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class    UserServiceImpl extends ServiceImpl<UsersDao , UserInfoEntity> implements UserService {
private final Map<String,String> verificationCodes = new HashMap<>();
    private final Map<String,UserInfoEntity> database=new HashMap<>();
    private final UserInfoEntity userInfoEntity = new UserInfoEntity();
    private final UsersDao usersDao;

    public UserServiceImpl(UsersDao usersDao) {
        this.usersDao = usersDao;
    }

    @Override
    public boolean addUser(UserInfoEntity user) {
        try {
            // 生成盐值
            String salt = PasswordUtils.generateSalt();
            user.setSalt(salt);

            // 对密码进行加密
            String hashedPassword = PasswordUtils.hashPassword(user.getUserPassword(), salt);
            user.setUserPassword(hashedPassword);

            // 保存用户信息到数据库
            return this.save(user);
        } catch (Exception e) {
            throw new RuntimeException("Error while adding user: " + e.getMessage(), e);
        }
    }

    @Override
    public UserInfoEntity getUserById(Long id) {
        return this.baseMapper.selectById(id);
    }


    @Override
    public boolean updateUser(UserInfoEntity user) {
        if(user.getUserId()==null){
            throw new IllegalArgumentException("User id can not be null");
        }
        try{
        if(user.getUserPassword()!=null&&!user.getUserPassword().isEmpty()){
            String salt = PasswordUtils.generateSalt();
            user.setUserPassword(salt);
            String Password = PasswordUtils.hashPassword(user.getUserPassword(),salt);
            user.setUserPassword(Password);

        }
        return this.updateById(user);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }

    }


    @Override
    public UserInfoEntity findUserByUsername(String username) {
            LambdaQueryWrapper<UserInfoEntity> queryWrapper=Wrappers.<UserInfoEntity>lambdaQuery();
            queryWrapper.eq(UserInfoEntity::getUserName,username);
            return this.getOne(queryWrapper);

    }

    @Override
    public IPage<UserInfoEntity> Query(UserInfoEntity userInfoEntity, int pageNo, int pageSize) {
     LambdaQueryWrapper<UserInfoEntity> wrapper = Wrappers.lambdaQuery();
     wrapper.eq(userInfoEntity.getUserId()!=null,UserInfoEntity::getUserId,userInfoEntity.getUserId());
        if (pageNo == 0) {
            pageNo = 1;
        }

        if (pageSize == 0) {
            pageSize = 10;
        }
        IPage<UserInfoEntity> page = Page.of((long)pageNo, (long)pageSize);
        return ((UsersDao)this.baseMapper).selectPage(page, wrapper);
    }

    @Override
    public IPage<UserInfoEntity> Query(UserInfoEntity user) {
        return Query(user,1,10);
    }

    @Override
    public UserInfoEntity findByEmail(String email) {
        List<UserInfoEntity> userInfoEntity = usersDao.selectList(null);
        for (UserInfoEntity user : userInfoEntity) {
            if (user.getUserEmail() != null && user.getUserEmail().equals(email)) {
                return user;
            }
        }
        return null;
    }

    public boolean validateVerificationCode(String email, String code) {
        String storedCode = verificationCodes.get(email);
        return storedCode != null && storedCode.equals(code);
    }

    public void registerUser(String username, String password)throws Exception {
        String salt=PasswordUtils.generateSalt();
        String hashedPassword=PasswordUtils.hashPassword(password,salt);
        UserInfoEntity userInfoEntity=new UserInfoEntity(username,hashedPassword,salt);
        this.save(userInfoEntity);
    }
    public boolean login(String username, String password) throws Exception{

        UserInfoEntity userInfoEntity=this.findUserByUsername(username);
        if(userInfoEntity==null){
            throw  new IllegalArgumentException("User not found");
        }

        boolean ishashedPassword = PasswordUtils.verifyPassword(password,userInfoEntity.getSalt(),userInfoEntity.getUserPassword());
        if (ishashedPassword) {
            System.out.println("Login successful!");
            return true;
        } else {
            System.out.println("Invalid credentials!");
            return false;
        }
    }

    @Override
    public int getUserClassByUsername(String username) {
        UserInfoEntity userInfoEntity=this.findUserByUsername(username);
        if(userInfoEntity==null){
            return -1;
        }
        return userInfoEntity.getUserClass();
    }
}
